﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/// 用于启用密码保护功能
/// 用户通过点击邮件里的链接来调用本页面
/// 需要GET参数：
/// userID —— 用户ID，明文，用于各种操作
/// _t —— 变量名无意义，实际指的是username，SHA1加密后转换为字符串
/// </summary>
public partial class emailVerified : System.Web.UI.Page
{
    /// <summary>
    /// 将参数中提供的数据和数据库中的数据比较，对应上即为验证成功
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        //检查参数是否齐全
        if (Request.QueryString["userID"] == null || Request.QueryString["_t"] == null)
        {
            Response.Redirect("noGETParameter.html", true);
            return;
        }
        else
        {
            //检查通过，通过userID从数据库中读取username，然后比较
            string userID = Request.QueryString["userID"];

            //从数据库中读取username
            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["connectionString"];
            using (SqlConnection dataBaseConnection = new SqlConnection(settings.ConnectionString))
            {
                dataBaseConnection.Open();

                string queryString = "SELECT username " +
                                     "FROM users " +
                                     "WHERE userID = @userID";
                SqlCommand command = new SqlCommand(queryString, dataBaseConnection);
                SqlParameter userIDParameter = new SqlParameter("@userID", userID);
                command.Parameters.Add(userIDParameter);
                SqlDataReader reader;
                try
                {
                    reader = command.ExecuteReader();
                }
                catch (Exception exception)
                {
                    main.InnerHtml = "数据库方面发生了错误，请联系我们以解决 AFTER GET username " + exception.Message; 
                    return;
                }

                //验证加密的用户名是否正确
                reader.Read();
                string username = reader["username"].ToString();
                if (Request.QueryString["_t"] != BitConverter.ToString(SHA1.Create().ComputeHash(Encoding.Unicode.GetBytes(username))).Replace("-", ""))
                {
                    main.InnerHtml = "我们无法为您启用密码保护功能，因为链接中的加密指令不正确";
                    return;
                }
                else
                {
                    //加密的用户名与数据库中的一致，将PasswordProtection表中Verified列改为1，如果存在Cookie[passwordProtectionStatus]则撤销之
                    reader.Close();

                    queryString = "UPDATE PasswordProtection " +
                                  "SET Verified = 1 " +
                                  "WHERE userID = @userID";
                    command.CommandText = queryString;
                    command.Parameters.Clear();
                    command.Parameters.Add(userIDParameter);
                    try
                    {
                        command.ExecuteNonQuery();
                    }
                    catch (Exception exception)
                    {
                        main.InnerHtml = "数据库方面发生了错误，请联系我们以解决 AFTER UPDATE PasswordProtection " + exception.Message;
                        return;
                    }

                    if (Request.Cookies["passwordProtectionStatus"] != null)
                    {
                        Response.Cookies["passwordProtectionStatus"].Expires = DateTime.Now.AddDays(-1);
                    }

                    //一切执行完毕，显示成功信息
                    main.InnerHtml = "<p>恭喜您 " + username + " 密保功能已经启用<br>如果您正在其他浏览器上使用WEP，请注销后重新登录以更新账户状态</p>";
                }
            }
        }
    }
}